package com.xinpu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinpu.entity.TStatus;
import com.xinpu.form.StatusForm;
import com.xinpu.service.ITStatusService;
import com.xinpu.service.OwnService;
import com.xinpu.vo.ResponseMessage;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@RequestMapping("/status")
public class StatusController {
    @Resource
    private ITStatusService itStatusService;

    /**
     * 状态列表
     *
     * @return
     */
    @GetMapping("/list")
    public ResponseMessage list(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size
    ) {
        return ResponseMessage.ok(itStatusService.page(new Page<>(page, size)));
    }

    /**
     * 添加或修改
     *
     * @param statusForm
     * @return
     */
    @PostMapping("/updateOrsave")
    public ResponseMessage updateOrsave(@RequestBody StatusForm statusForm) {
        TStatus tStatus = new TStatus();
        String name = statusForm.getName();
        QueryWrapper<TStatus> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        wrapper.eq("tenant_id", OwnService.getLoginer().getTenantId()).or().eq("tenant_id", "0");
        TStatus status = itStatusService.getOne(wrapper);
        if (statusForm.getId() != null) {
            tStatus.setId(statusForm.getId());
            if (status != null) {
                if (!status.getId().equals(statusForm.getId())) {
                    return ResponseMessage.error("状态重复,请重新提交");
                }
            }
            tStatus.setName(name);
            tStatus.setSid(0);
            itStatusService.saveOrUpdate(tStatus);
            return ResponseMessage.ok();
        }
        if (status == null) {
            tStatus.setName(name);
            tStatus.setSid(0);
            itStatusService.saveOrUpdate(tStatus);
            return ResponseMessage.ok();
        }
        return ResponseMessage.error("状态重复,请重新创建");
    }

    /**
     * 删除
     *
     * @return
     */
    @PostMapping("/remove")
    public ResponseMessage remove(@RequestBody StatusForm statusForm) {
        return ResponseMessage.ok(itStatusService.removeById(statusForm.getId()));
    }
}
